package com.iotechn.uninotify.service.open;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.iotechn.uninotify.compent.CacheComponent;
import com.iotechn.uninotify.domain.DeveloperUserDO;
import com.iotechn.uninotify.exception.NotifyExceptionDefinition;
import com.iotechn.uninotify.exception.NotifyServiceException;
import com.iotechn.uninotify.exception.ServiceException;
import com.iotechn.uninotify.mapper.DeveloperUserMapper;
import com.iotechn.uninotify.service.biz.WxMpBizService;
import com.iotechn.uninotify.util.GeneratorUtil;
import com.iotechn.uninotify.util.RequestUtil;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: rize
 * Date: 2019/12/26
 * Time: 16:23
 */
@Service("developerService")
public class DeveloperServiceImpl implements DeveloperService {

    private static final Logger logger = LoggerFactory.getLogger(DeveloperServiceImpl.class);

    @Autowired
    private DeveloperUserMapper developerUserMapper;

    @Autowired
    private WxMpBizService wxMpBizService;

    @Autowired
    private CacheComponent cacheComponent;

    private OkHttpClient okHttpClient = new OkHttpClient();

    public static final String CA_TMP_TOKEN = "CA_TMP_TOKEN_";

    @Override
    public String getRegisterUrl(String userId) throws ServiceException {
        try {
            //1. 检验是否已经存在此用户了
            Integer count = developerUserMapper.selectCount(new QueryWrapper<DeveloperUserDO>().eq("user_id", userId).eq("app_id", RequestUtil.getDeveloper().getAppId()));
            if (count > 0) {
                throw new NotifyServiceException(NotifyExceptionDefinition.NOTIFY_USER_HAS_BEEN_REGISTERED);
            }
            //2. 生成临时令牌 & 生成微信绑定URL
            String accessToken = wxMpBizService.getAccessToken();
            // 临时令牌用于回调时，定位当前请求的用户Id。因为用户Id不能明文Id不方便出现外面。
            String tmpToken = GeneratorUtil.genUUId();
            Map<String, String> tokenObj = new HashMap<>();
            tokenObj.put("appId", RequestUtil.getDeveloper().getAppId());
            tokenObj.put("appSecret", RequestUtil.getDeveloper().getAppSecret());
            tokenObj.put("userId", userId);
            tokenObj.put("notifyUrl", RequestUtil.getDeveloper().getNotifyUrl());
            cacheComponent.putObj(CA_TMP_TOKEN + tmpToken, tokenObj, 5 * 60);
            JSONObject paramObj = new JSONObject();
            paramObj.put("expire_seconds", 5 * 60);
            paramObj.put("action_name", "QR_STR_SCENE");
            JSONObject scene = new JSONObject();
            JSONObject sceneStr = new JSONObject();
            scene.put("scene", sceneStr);
            sceneStr.put("scene_str", tmpToken);
            paramObj.put("action_info", scene);
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, paramObj.toJSONString());
            String json = okHttpClient.newCall(new Request.Builder().url("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken).post(body).build()).execute().body().string();
            JSONObject resObj = JSONObject.parseObject(json);
            String url = resObj.getString("url");
            if (StringUtils.isEmpty(url)) {
                logger.info("[微信获取二维码] 回复不正确 response:" + json);
                throw new NotifyServiceException(NotifyExceptionDefinition.NOTIFY_WX_RESPONSE_FAILED);
            }
            return url;
        } catch (IOException e) {
            throw new NotifyServiceException(NotifyExceptionDefinition.NOTIFY_IO_EXCEPTION);
        }
    }

    @Override
    public Boolean isRegister(String userId) throws ServiceException {
        return developerUserMapper.selectCount(new QueryWrapper<DeveloperUserDO>().eq("user_id", userId).eq("app_id", RequestUtil.getDeveloper())) > 0;
    }
}
